<?php
namespace Sys\Controller;

use Todo\Controller\BackendController;
use Todo\Util\ArrayUtil;

/**
 * Class MenuController 系统菜单
 * @package Sys\Controller
 */
class MenuController extends BackendController
{

    protected function _initialize()
    {
        parent::_initialize();
    }

    public function _before_index()
    {
        $appId = I('get.app_id');
        $appList = D('Todo/Sys/Application')->order('sort ASC')->select();
        if (!$appId) $appId = $appList[0]['id'];
        $this->assign('appList', $appList);
        $this->assign('appId', $appId);
    }

    /**
     * 基于角色判断的应用权限菜单
     */
    public function tree()
    {
        $appId = I('get.app_id');
        if (!$appId) $this->apiError('您没有权限1');
        //var_dump($this->_user);
        if ($this->_user['is_super']) {
            $menuList = D('Todo/Sys/Menu')->field('id,pid,type,url,title text')->where(array('app_id' => $appId))->select();
        } else {
            $menuIds = D('Todo/Sys/RoleMenu')->where(array('role_id' => array('in', $this->_user['roles'])))->getField('menu_id',true);
            if (!$menuIds) $this->apiError('您没有权限2');

            $menuList = D('Todo/Sys/Menu')->field('id,pid,type,url,title text')->where(array('app_id' => $appId, 'id' => array('in', $menuIds)))->select();
            $pids = ArrayUtil::getColumn($menuList, 'pid');
            if ($pids) {
                $ids = ArrayUtil::getColumn($menuList, 'id');
                $where = "id in (" . implode(',', $pids) . ") AND id NOT IN (" . implode(',', $ids) . ")";
                $menuList2 = D('Todo/Sys/Menu')->field('id,pid,type,url,title text')->where($where)->select();
                $menuList = array_merge($menuList, $menuList2);


                $pids = ArrayUtil::getColumn($menuList2, 'pid');
                if ($pids) {
                    $ids = ArrayUtil::getColumn($menuList2, 'id');
                    $where = "id in (" . implode(',', $pids) . ") AND id NOT IN (" . implode(',', $ids) . ")";
                    $menuList3 = D('Todo/Sys/Menu')->field('id,pid,type,url,title text')->where($where)->select();
                    $menuList = array_merge($menuList, $menuList3);
                }
            }
        }

        $data = ArrayUtil::getTree($menuList);
        $this->apiSuccess($data);
    }

}